package com.future.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.future.allUtils.constants.RedisCacheConstants;
import com.future.allUtils.utils.SecurityUtils;
import com.future.domain.*;
import com.future.domain.Class;
import com.future.domain.DTO.ChatListDTO;
import com.future.domain.DTO.ChatRoomPrivateDTO;
import com.future.domain.DTO.PageDTO;
import com.future.domain.DTO.PeopleDTO;
import com.future.mapper.*;
import com.future.service.ChatMemberService;
import com.future.service.ChatMessageService;
import com.future.service.ChatRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ChatRoomImpl implements ChatRoomService {
    @Autowired
    private ChatRoomMapper chatRoomMapper;
    @Autowired
    private ChatRoomMemberMapper roomMemberMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ChatMemberService memberService;
    @Autowired
    private ChatMessageService messageService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     *保存聊天室信息
     * @param chatroom
     */
    @Override
    public void saveChatRoom(ChatRoom chatroom) {
        try {
            // 1. 保存到数据库
            if (chatroom!=null) {
                Long currentUserId=SecurityUtils.getCurrentUserId();
                chatroom.setCreatedAt(new Date());
                chatroom.setCreatedBy(currentUserId);
                chatRoomMapper.insert(chatroom);
                Long roomId=chatroom.getId();

                // 2. 更新缓存
                ChatListDTO chatListDTO = chatRoomMapper.selectChatDTO(roomId, currentUserId);
                String roomKey = RedisCacheConstants.USER_CHAT_ROOMS_PREFIX + currentUserId;
                String chatRoom = objectMapper.writeValueAsString(chatListDTO);
                stringRedisTemplate.opsForZSet().add(roomKey,chatRoom,chatListDTO.getCreatedAt().getTime());
                stringRedisTemplate.expire(roomKey,7, TimeUnit.DAYS);
            }

        } catch (Exception e) {
            log.error("保存聊天室失败", e);
        }
    }
    @Override
    public Result getUserChatRoom() {
        Long currentUserId=SecurityUtils.getCurrentUserId();
        try {
                List<ChatListDTO>chatListDTOS = chatRoomMapper.selectAllChatList(currentUserId);
                 return Result.ok(chatListDTOS);
            }
        catch (Exception e) {
            log.error("获取用户聊天室列表失败", e);
            return Result.fail("获取用户聊天室列表失败：" + e.getMessage());
        }
    }
    /**
     * 判断私聊是聊天室是否存在，不存在就创建
     */
    @Override
    @Transactional
    public Result getOrCreatePrivateChatRoom(String userIdB1) {
        try {
            if(userIdB1==null||userIdB1.trim().isEmpty())
            {
                return Result.fail("私聊用户id为空");
            }
            Long userIdB=Long.valueOf(userIdB1);
            Long currentUserId = SecurityUtils.getCurrentUserId();
            User user1=userMapper.selectById(currentUserId);
            User user = userMapper.selectById(userIdB);
            if (user1== null) {
                return Result.fail("当前用户不存在"); // 提前阻断
            }
            if (user == null) {
                return Result.fail("用户不存在");
            }
            if (currentUserId.equals(userIdB)) {
                return Result.fail("不能向自己发送私聊消息");
            }
            Long existingRoomId = chatRoomMapper.isChatRoomExisting(currentUserId, userIdB);
            if (existingRoomId != null) {
                ChatRoom chatRoom = chatRoomMapper.selectById(existingRoomId);
                ChatRoomPrivateDTO privateDTO=new ChatRoomPrivateDTO(chatRoom.getRoomName(), chatRoom.getRoomType(),
                        chatRoom.getCreatedBy().toString(),
                        chatRoom.getCreatedAt(),
                        chatRoom.getId().toString(),
                        user.getId().toString(),
                        user.getUsername(),
                        user.getAvatar());
                Map<String, Object> resultmap = new HashMap<>();
                resultmap.put("msg","聊天室已存在");
                resultmap.put("chatRoom", privateDTO);
                return Result.ok(resultmap);
            }
            //不存在创建聊天室
            ChatRoom chatRoom = new ChatRoom();
            chatRoom.setRoomType("私聊") ;
            chatRoom.setRoomName(user1.getUsername()+"与"+user.getUsername());
            chatRoom.setCreatedBy(currentUserId);
            chatRoom.setCreatedAt(new Date());
            chatRoomMapper.insert(chatRoom);
            Long roomId = chatRoom.getId();

            saveChatRoom(chatRoom);
            memberService.saveChatRoomMember(roomId, Arrays.asList(currentUserId, userIdB));
            Map<String, Object> resultmap = new HashMap<>();
            ChatRoom chatRoom1 = chatRoomMapper.selectById(roomId);
            ChatRoomPrivateDTO privateDTO1=new ChatRoomPrivateDTO(chatRoom1.getRoomName(), chatRoom1.getRoomType(),
                    chatRoom1.getCreatedBy().toString(),
                    chatRoom1.getCreatedAt(),
                    chatRoom1.getId().toString(),
                    user.getId().toString(),
                    user.getUsername(),
                    user.getAvatar());
            resultmap.put("msg","创建新的聊天室");
            resultmap.put("chatRoom", privateDTO1);
            return Result.ok(resultmap);
        } catch (Exception e) {
            log.error("创建/获取私聊房间失败", e);
            return Result.fail("创建私聊失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result creatChatRoom(Long classId) {
        try {
            Long userId=SecurityUtils.getCurrentUserId();
            User user = userMapper.selectById(userId);
            if(user==null)
            {
                return Result.fail("请先登录");
            }
            if(classId==null)
            {
                return Result.fail("班级创造失败");
            }
            List<Integer> roles = chatRoomMapper.selectUserRole(userId);
            if(!roles.contains(2))
            {
                return Result.fail("仅老师创建班级");
            }
            LambdaQueryWrapper<ChatRoom> chatRoomLambdaQueryWrapper=new LambdaQueryWrapper<>();
            chatRoomLambdaQueryWrapper.eq(ChatRoom::getClassId,classId);
            ChatRoom chatRoom1 = chatRoomMapper.selectOne(chatRoomLambdaQueryWrapper);
            if(chatRoom1!=null)
            {
                Long roomId=chatRoom1.getId();
                Map<String,Long> resultMap=new ConcurrentHashMap<>();
                resultMap.put("classId",classId);
                resultMap.put("roomId",roomId);
                return Result.ok(resultMap);
            }
            List<Long> usersId = roomMemberMapper.selectUserIdByClassId(classId);
            String className = chatRoomMapper.selectClassName(classId);
            if(usersId==null)
            {
                usersId=new ArrayList<>();
            }
            if(!usersId.contains(userId))
            {
                usersId.add(userId);
            }
            ChatRoom chatRoom = new ChatRoom(null,className, "群聊", classId, userId, new Date());
            chatRoomMapper.insert(chatRoom);
            Long roomId = chatRoom.getId();
            //更新缓存
            saveChatRoom(chatRoom);
            memberService.saveChatRoomMember(roomId,usersId);
            Map<String,Long> resultMap=new ConcurrentHashMap<>();
            resultMap.put("classId",classId);
            resultMap.put("roomId",roomId);
            return Result.ok(resultMap);
        }catch (Exception e)
        {
            log.error("创建班级及班级群聊失败", e);
            return Result.fail("创建班级及班级群聊失败");
        }
    }
    @Override
    public Result classList()
    {
        LoginUserDetails currentUser = SecurityUtils.getCurrentUser();
        Long currentUserId = SecurityUtils.getCurrentUserId();
        List<Integer> roles = chatRoomMapper.selectUserRole(currentUserId);
        if(!roles.contains(2))
        {
            return Result.fail("非教师没有权限");
        }
        List<Class> classes=chatRoomMapper.classListByteacherId(currentUser.getUser().getId());
        if(classes==null||classes.isEmpty())
        {
            return Result.ok("该教师没有管理的班级");
        }
        return Result.ok(classes);
    }
    @Override
    public Result creatCounselingroom(String userId1) {
        try {
            if(userId1==null||userId1.trim().isEmpty())
            {
                return Result.fail("用户id为空");
            }
            Long userId=Long.valueOf(userId1);
            Long currentUserId = SecurityUtils.getCurrentUserId();
            User user = userMapper.selectById(userId);
            List<Integer> roles = chatRoomMapper.selectUserRole(userId);
            if (currentUserId.equals(userId)||!roles.contains(3)) {
                return Result.fail("请选择心理医生");
            }
            Long existingRoomId = chatRoomMapper.isChatRoomExisting(currentUserId, userId);
            if (existingRoomId != null) {
                ChatRoom chatRoom = chatRoomMapper.selectById(existingRoomId);
                ChatRoomPrivateDTO privateDTO=new ChatRoomPrivateDTO(chatRoom.getRoomName(), chatRoom.getRoomType(),
                        chatRoom.getCreatedBy().toString(),
                        chatRoom.getCreatedAt(),
                        chatRoom.getId().toString(),
                        user.getId().toString(),
                        user.getUsername(),
                        user.getAvatar());
                Map<String, Object> resultmap = new HashMap<>();
                resultmap.put("msg","聊天室已存在");
                resultmap.put("chatRoom", privateDTO);
                return Result.ok(resultmap);
            }
            //不存在创建咨询室
            ChatRoom chatRoom = new ChatRoom();
            chatRoom.setRoomType("心理咨询");
            chatRoom.setRoomName("心理咨询室-"+user.getUsername());
            chatRoom.setCreatedBy(currentUserId);
            chatRoom.setCreatedAt(new Date());
            chatRoomMapper.insert(chatRoom);
            Long roomId = chatRoom.getId();

            saveChatRoom(chatRoom);
            memberService.saveChatRoomMember(roomId, Arrays.asList(currentUserId, userId));
            Map<String, Object> resultmap = new HashMap<>();
            ChatRoom chatRoom1 = chatRoomMapper.selectById(roomId);
            ChatRoomPrivateDTO privateDTO1=new ChatRoomPrivateDTO(chatRoom1.getRoomName(), chatRoom1.getRoomType(),
                    chatRoom1.getCreatedBy().toString(),
                    chatRoom1.getCreatedAt(),
                    chatRoom1.getId().toString(),
                    user.getId().toString(),
                    user.getUsername(),
                    user.getAvatar());
            resultmap.put("msg","创建新的聊天室");
            resultmap.put("chatRoom", privateDTO1);
            return Result.ok(resultmap);
        } catch (Exception e) {
            log.error("心理咨询失败", e);
            return Result.fail("心理咨询失败");
        }
    }

    @Override
    public Result DoctorsList(Integer pageNum,Integer pageSize) {
        if(pageNum<1) pageNum=1;
        if(pageSize<1) pageNum=10;
        Integer start = (pageNum - 1) * pageSize;
        List<User> psychologistUsers = chatRoomMapper.selectpsychologistUsers(start,pageSize);
        Long total=chatRoomMapper.countUserNum();
        Long totalPage=(total+pageSize-1)/pageSize;
        List<PeopleDTO> peoples= psychologistUsers.stream()
                .map(user -> new PeopleDTO(
                        user.getAvatar(),   // 映射 avatar
                        user.getId().toString(),       // 映射 id -> userId
                        user.getUsername(),  // 映射 username
                        user.getBio(),
                        user.getCreatedAt()
                ))
                .collect(Collectors.toList());
        PageDTO<PeopleDTO> pageDTO=new PageDTO<>();
        pageDTO.setRows(peoples)    // 当前页数据
                .setTotal(total)              // 总条数
                .setTotalPage(totalPage);
        return Result.ok(pageDTO);
    }

}
